local hx__chouka = fk.CreateSkill{
  name = "hx__chouka",
  tags = { Skill.Compulsory, Skill.Permanent},
}

hx__chouka:addEffect(fk.TargetConfirmed, {
  anim_type = "defensive",
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(hx__chouka.name) and data.from ~= player and data:isOnlyTarget(target)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local from = data.from
    if player.general ~= "hxgod__doro" and player.deputyGeneral ~= "hxgod__doro" then
      player.room:doBroadcastNotify("ShowToast", "觊觎抽卡的力量吗？不好意思，神临doro觉得不行，决定改为让你摸牌并清除了所有已抽卡标记……")
      player.room:drawCards(player, 2, self.name)
      for _, p in ipairs(player.room.alive_players) do
        if p:getMark("@hx__chouka_count") > 0 then
          player.room:setPlayerMark(p, "@hx__chouka_count", 0)
        end
      end
    return false end
    room:notifySkillInvoked(player, self.name, "special")
    if player:getMark("hx__chouka_broadcast") == 0 then
      if player.room:askToSkillInvoke(player, {skill_name = self.name, prompt = "抽卡：是否播放doroの小曲？（此时机每局只能播放一次哦）"}) then
        room:broadcastPlaySound("./packages/huixiangkill/audio/skill/#hx__doromusic&")
        room:addPlayerMark(player,"hx__chouka_broadcast")
      end
    end
    room:doIndicate(player, {from})
    room:addPlayerMark(from,"@hx__chouka_count", 1)
    local card1 = room:getCardsFromPileByRule(".", 1,"allPiles")
    room:doBroadcastNotify("ShowToast", "doro的抽卡结果是……")
    room:delay(900)
    player:showCards(card1)
    local card2 = room:getCardsFromPileByRule(".", 1,"allPiles")
    room:doBroadcastNotify("ShowToast", "该角色的抽卡结果是……")
    room:delay(900)
    from:showCards(card2)
    local n = 0
    local type1 = Fk:getCardById(card1[1]).type
    local type2 = Fk:getCardById(card2[1]).type
    local suit1 = Fk:getCardById(card1[1]).suit
    local suit2 = Fk:getCardById(card2[1]).suit
    local num1 = Fk:getCardById(card1[1]).number
    local num2 = Fk:getCardById(card2[1]).number
    local name1 = Fk:getCardById(card1[1]).name
    local name2 = Fk:getCardById(card2[1]).name
    if type1 == type2 then
      n = n + 1
    end
    if suit1 == suit2 then
      n = n + 1
    end
    if num1 == num2 then
      n = n + 1
    end
    if name1 == name2 then
      n = n + 1
    end
    room:sendLog{
      type = "【抽卡】相同项的数量是%arg！！！",
      arg = n,
    }
    room:delay(1000)
    if n == 4 then
      if not from.dead then
        room:setPlayerProperty(from, "role", player.role)
      end
      room:doBroadcastNotify("ShowToast", "【抽卡】相同项的数量是4！！！！恭喜该角色更改身份为与doro相同并与doro一起获得游戏胜利！")
      if player.room:askToSkillInvoke(player, {
        skill_name = self.name,
        prompt = "抽卡：是否播放doroの小曲？"}) then
        room:broadcastPlaySound("./packages/huixiangkill/audio/skill/#hx__doromusic&")
      end
      room:delay(2000)
      if player.role == "lord" or player.role == "loyalist" then
        player.room:gameOver("lord+loyalist")
      else
        player.room:gameOver(player.role)
      end
    elseif n == 3 then
      room:doBroadcastNotify("ShowToast", "【抽卡】相同项的数量是3！！！恭喜该角色与doro各加两点体力上限并回满体力！")
      if player.room:askToSkillInvoke(player, {
        skill_name = self.name,
        prompt = "抽卡：是否播放doroの小曲？"}) then
        room:broadcastPlaySound("./packages/huixiangkill/audio/skill/#hx__doromusic&")
      end
      room:changeMaxHp(player, 2)
      room:recover({
        who = player,
        num = player:getLostHp(),
        skillName = self.name
      })
      room:changeMaxHp(from, 2)
      room:recover({
        who = from,
        num = from:getLostHp(),
        skillName = self.name
      })
    elseif n == 2 then
      room:doBroadcastNotify("ShowToast", "【抽卡】相同项的数量是2！！恭喜该角色与doro交换位置然后摸两张牌并令doro执行一个额外的回合！") 
      room:swapSeat(from, player)
      from:drawCards(2,self.name)
      player:gainAnExtraTurn(false)
    elseif n == 1 then
      room:doBroadcastNotify("ShowToast", "【抽卡】相同项的数量是1！太遗憾了该角色的体力值变成一点了。。") 
      if not from.dead then
        room:loseHp(from, from.hp - 1, self.name)
        local targets = table.filter(room:getAlivePlayers(), function (p) return p.id ~= player.id end)
        local tos = room:askToChoosePlayers(from, {
          min_num = 1,
          max_num = 1,
          targets = targets,
          skill_name = self.name,
          prompt = "令一名角色将武将替换为随机非神势力的doro（包括标刘备）!",
          cancelable = true,
        })
        if #tos > 0 then
          local to = tos[1]
          local generals = {}
          local doros = {}
          for _, p in pairs(room.alive_players) do
            local general = Fk.generals[p.general]
            if general.package.name == "hxdoro" then
              table.insert(doros, general.name)
            end
            if p.deputyGeneral ~= "" then
              local general2 = Fk.generals[p.deputyGeneral]
              if general2.package.name == "hxdoro" then
                table.insert(doros, general.name)
              end
            end
          end
          for _, general in pairs(Fk.generals) do
            if not table.contains(doros, general.name) then
              if general.package.name == "hxdoro" or general.name == "liubei" then
                table.insert(generals, general.name)
              end
            end
          end
          room:changeHero(to, table.random(generals), false, false, true)
        end
      end
    elseif n == 0 then
      room:doBroadcastNotify("ShowToast", "【抽卡】相同项的数量是0。。太遗憾了该角色死亡了，但是别担心，doro会复活你的！") 
      local to_revive = {room:getTag("hx__chouka_dead")} or {}
      room:killPlayer({who = from})
      if #to_revive > 0 then
        room:revivePlayer(to_revive[1], true)
      end
      room:setTag("hx__chouka_dead", from)
    --  room.logic:breakEvent()
      data:cancelTarget(player)
    end
  end,
})

hx__chouka:addEffect(fk.PreHpLost, {
  anim_type = "defensive",
  can_trigger = function(self, event, target, player, data)
    local targets = table.filter(player.room:getOtherPlayers(player), function (p) return p:getMark("@hx__chouka_count") > 0 end)
    if #targets >= #player.room:getOtherPlayers(player) then return end
    if player:hasSkill(hx__chouka.name) then
      return player == target
    end
  end,
  on_use = function(self, event, target, player, data)
    if player.general ~= "hxgod__doro" and player.deputyGeneral ~= "hxgod__doro" then
      player.room:doBroadcastNotify("ShowToast", "觊觎抽卡的力量吗？不好意思，神临doro觉得不行，决定改为让你摸牌并清除了所有已抽卡标记……")
      player.room:drawCards(player, 2, self.name)
      for _, p in ipairs(player.room.alive_players) do
        if p:getMark("@hx__chouka_count") > 0 then
          player.room:setPlayerMark(p, "@hx__chouka_count", 0)
        end
      end
    return false end
    data.num = 0
  end,
})

hx__chouka:addEffect(fk.DamageInflicted, {
  anim_type = "defensive",
  can_trigger = function(self, event, target, player, data)
    local targets = table.filter(player.room:getOtherPlayers(player), function (p) return p:getMark("@hx__chouka_count") > 0 end)
    if #targets >= #player.room:getOtherPlayers(player) then return end
    if player:hasSkill(hx__chouka.name) then
      return player == target
    end
  end,
  on_use = function(self, event, target, player, data)
    if player.general ~= "hxgod__doro" and player.deputyGeneral ~= "hxgod__doro" then
      player.room:doBroadcastNotify("ShowToast", "觊觎抽卡的力量吗？不好意思，神临doro觉得不行，决定改为让你摸牌并清除了所有已抽卡标记……")
      player.room:drawCards(player, 2, self.name)
      for _, p in ipairs(player.room.alive_players) do
        if p:getMark("@hx__chouka_count") > 0 then
          player.room:setPlayerMark(p, "@hx__chouka_count", 0)
        end
      end
    return false end
    data:preventDamage()
  end,
})

hx__chouka:addEffect(fk.BeforeMaxHpChanged, {
  anim_type = "defensive",
  can_trigger = function(self, event, target, player, data)
    local targets = table.filter(player.room:getOtherPlayers(player), function (p) return p:getMark("@hx__chouka_count") > 0 end)
    if #targets >= #player.room:getOtherPlayers(player) then return end
    if player:hasSkill(hx__chouka.name) then
      return player == target and data.num < 0
    end
  end,
  on_use = function(self, event, target, player, data)
    if player.general ~= "hxgod__doro" and player.deputyGeneral ~= "hxgod__doro" then
      player.room:doBroadcastNotify("ShowToast", "觊觎抽卡的力量吗？不好意思，神临doro觉得不行，决定改为让你摸牌并清除了所有已抽卡标记……")
      player.room:drawCards(player, 2, self.name)
      for _, p in ipairs(player.room.alive_players) do
        if p:getMark("@hx__chouka_count") > 0 then
          player.room:setPlayerMark(p, "@hx__chouka_count", 0)
        end
      end
    return false end
    data.num = 0
  end,
})

hx__chouka:addEffect(fk.AskForPeachesDone, {
  anim_type = "defensive",
  is_delay_effect = true,
  can_trigger = function(self, event, target, player, data)
    local targets = table.filter(player.room:getOtherPlayers(player), function (p) return p:getMark("@hx__chouka_count") > 0 end)
    if #targets >= #player.room:getOtherPlayers(player) then return end
    if player:hasSkill(hx__chouka.name) then
      return player == target and (event == fk.AskForPeachesDone and player.hp <= 0 and player.dying)
    end
  end,
  on_use = function(self, event, target, player, data)
    if player.general ~= "hxgod__doro" and player.deputyGeneral ~= "hxgod__doro" then
      player.room:doBroadcastNotify("ShowToast", "觊觎抽卡的力量吗？不好意思，神临doro觉得不行，决定改为让你摸牌并清除了所有已抽卡标记……")
      player.room:drawCards(player, 2, self.name)
      for _, p in ipairs(player.room.alive_players) do
        if p:getMark("@hx__chouka_count") > 0 then
          player.room:setPlayerMark(p, "@hx__chouka_count", 0)
        end
      end
    return false end
    data.ignoreDeath = true
  end,
})

hx__chouka:addEffect(fk.BeforeGameOverJudge, {
  anim_type = "defensive",
  can_trigger = function(self, event, target, player, data)
    local targets = table.filter(player.room:getOtherPlayers(player), function (p) return p:getMark("@hx__chouka_count") > 0 end)
    if #targets >= #player.room:getOtherPlayers(player) then return end
    if target == player then
      return player:hasSkill(hx__chouka.name, false, true)
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if player.general ~= "hxgod__doro" and player.deputyGeneral ~= "hxgod__doro" then
      player.room:doBroadcastNotify("ShowToast", "觊觎抽卡的力量吗？不好意思，神临doro觉得不行，决定改为让你摸牌并清除了所有已抽卡标记……")
      player.room:drawCards(player, 2, self.name)
      for _, p in ipairs(player.room.alive_players) do
        if p:getMark("@hx__chouka_count") > 0 then
          player.room:setPlayerMark(p, "@hx__chouka_count", 0)
        end
      end
    return false end
    player._splayer:setDied(false)
    room:setPlayerRest(player, 1)
  end,
})

hx__chouka:addLoseEffect(function (self, player, is_death)
  if not (player.general == "hxgod__doro" or player.deputyGeneral == "hxgod__doro") then
    player.room:doBroadcastNotify("ShowToast", "要想重获抽卡，非得是神临doro才行……")
    player.room:doBroadcastNotify("ShowToast", "（已清除了所有已抽卡标记……）")
    for _, p in ipairs(player.room.alive_players) do
      if p:getMark("@hx__chouka_count") > 0 then
        player.room:setPlayerMark(p, "@hx__chouka_count", 0)
      end
    end
  else
    local targets = table.filter(player.room:getOtherPlayers(player), function (p) return p:getMark("@hx__chouka_count") > 0 end)
    if #targets < #player.room:getOtherPlayers(player) then
      player.room:doBroadcastNotify("ShowToast", "还不是时候哦！神临doro决定放你一马并清除了所有已抽卡标记~")
      player.room:handleAddLoseSkills(player, "hx__chouka", nil, true, true)
    end
    for _, p in ipairs(player.room.alive_players) do
      if p:getMark("@hx__chouka_count") > 0 then
        player.room:setPlayerMark(p, "@hx__chouka_count", 0)
      end
    end
  end
end)

hx__chouka:addEffect(fk.BeforePropertyChange, {
  is_delay_effect = true,
  can_trigger = function (self, event, target, player, data)
    local targets = table.filter(player.room:getOtherPlayers(player), function (p) return p:getMark("@hx__chouka_count") > 0 end)
    if #targets >= #player.room:getOtherPlayers(player) then return end
    if target == player and player:hasSkill(hx__chouka.name) then
      return data.from == player and (data.general ~= "hxgod__doro" and player.general == "hxgod__doro") or
       (data.deputyGeneral ~= "hxgod__doro" and player.deputyGeneral == "hxgod__doro")
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if player.general ~= "hxgod__doro" and player.deputyGeneral ~= "hxgod__doro" then
      player.room:doBroadcastNotify("ShowToast", "觊觎抽卡的力量吗？不好意思，神临doro觉得不行，决定改为让你摸牌并清除了所有已抽卡标记……")
      player.room:drawCards(player, 2, self.name)
      for _, p in ipairs(player.room.alive_players) do
        if p:getMark("@hx__chouka_count") > 0 then
          player.room:setPlayerMark(p, "@hx__chouka_count", 0)
        end
      end
    return false end
    if player.room:askToSkillInvoke(player, {
      skill_name = self.name,
      prompt = "抽卡：是否播放doroの小曲？"}) then
      player.room:broadcastPlaySound("./packages/huixiangkill/audio/skill/#hx__doromusic&")
    end
    player.room:doBroadcastNotify("ShowToast", "对doro下手，你到底要做什么？！神临doro决定在该回合结束后惩罚你！")
    for _, p in ipairs(player.room.alive_players) do
      if p:getMark("@hx__chouka_count") > 0 then
        player.room:setPlayerMark(p, "@hx__chouka_count", 0)
      end
    end
    if data.general ~= "hxgod__doro" and player.general == "hxgod__doro" then
      data.general = "hxgod__doro"
    end
    if data.deputyGeneral ~= "hxgod__doro" and player.deputyGeneral == "hxgod__doro" then
      data.deputyGeneral = "hxgod__doro"
    end
    if not player:hasSkill("hx__doro_kill", true) then
      room:handleAddLoseSkills(player, "hx__doro_kill")
      room.logic:getCurrentEvent():findParent(GameEvent.Turn):addCleaner(function()
        room:handleAddLoseSkills(player, "-hx__doro_kill")
      end)
    end
    player:gainAnExtraPhase(Player.Play,hx__chouka.name, true)
  end,
})


hx__chouka:addEffect(fk.Deathed, {
  mute = true,
  can_trigger = function(self, event, target, player, data)
    return player.dead and player.rest > 0 and player:hasSkill(self.name, true, true)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if player.general ~= "hxgod__doro" and player.deputyGeneral ~= "hxgod__doro" then
      player.room:doBroadcastNotify("ShowToast", "觊觎抽卡的力量吗？不好意思，神临doro觉得不行，决定改为让你摸牌并清除了所有已抽卡标记……")
      player.room:drawCards(player, 2, self.name)
      for _, p in ipairs(player.room.alive_players) do
        if p:getMark("@hx__chouka_count") > 0 then
          player.room:setPlayerMark(p, "@hx__chouka_count", 0)
        end
      end
    return false end
    room:revivePlayer(player, true, "rest")
    room:setPlayerRest(player, 0)
    room:setPlayerProperty(player, "maxHp", 3)
    room:setPlayerProperty(player, "hp", 3)
    --补偿一下
    room:doBroadcastNotify("ShowToast", "你杀死了没有抽完卡的doro！神临doro决定复活并在该回合内惩罚你！")
    for _, p in ipairs(player.room.alive_players) do
      if p:getMark("@hx__chouka_count") > 0 then
        player.room:setPlayerMark(p, "@hx__chouka_count", 0)
      end
    end
    room:delay(114)
    room:delay(514)
    player:drawCards(9, hx__chouka.name)
    player:drawCards(5, hx__chouka.name)
    player:drawCards(2, hx__chouka.name)
    player:drawCards(7, hx__chouka.name)
    room:addPlayerMark(player, MarkEnum.BypassTimesLimit.. "-turn")
    room:addPlayerMark(player, MarkEnum.BypassDistancesLimit.. "-turn")
    for _, p in ipairs(room:getOtherPlayers(player)) do
      room:addTableMark(p, MarkEnum.MarkArmorInvalidFrom.. "-turn")
      room:addTableMark(p, MarkEnum.UncompulsoryInvalidity.. "-turn")
      room:setPlayerMark(p, "@hx__chouka_count", 0)
    end
    if not player:hasSkill("hx__doro_kill", true) then
      room:handleAddLoseSkills(player, "hx__doro_kill")
      room.logic:getCurrentEvent():findParent(GameEvent.Turn):addCleaner(function()
        room:handleAddLoseSkills(player, "-hx__doro_kill")
      end)
    end
    player:gainAnExtraPhase(Player.Play,hx__chouka.name, false)
  end,
})


return hx__chouka
